package com.kuaifawu.lwnlawyerclient.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.CircularImage;
import com.kuaifawu.lwnlawyerclient.Lib.KFWActivityCenter;
import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.model.PhotoModel;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.ui.PhotoSelectorActivity;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_lawyerInfo;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by wyk123 on 2015/4/20.
 */
public class LWNEditProfileActivity extends Activity implements View.OnClickListener {
    @ViewInject(R.id.line_pic)
    private LinearLayout line_pic;
    @ViewInject(R.id.line_signature)
    private LinearLayout line_signature;
    @ViewInject(R.id.line_intro)
    private LinearLayout line_intro;
    @ViewInject(R.id.signature_textview)
    private TextView signature_textview;
    @ViewInject(R.id.intro_textview)
    private TextView intro_textview;
    @ViewInject(R.id.select_pic)
    private LinearLayout select_pic;
    @ViewInject(R.id.select_picView)
    private CircularImage select_picView;
    @ViewInject(R.id.real_name)
    private TextView real_name;
    @ViewInject(R.id.profile_back)
    private ImageButton profile_back;
    private LWNEditProfileActivity activity;
    private String[] items = new String[] { "选择本地图片", "拍照","取消" };
    private String picPath="";//要上传的图片的地址
    private Bitmap photo = null;//要上传的图片
    private Bitmap newphoto=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editprofile);
        inItView();
    }
    private void inItView(){
        ViewUtils.inject(this);
        activity=this;
        line_pic.setOnClickListener(this);
        line_signature.setOnClickListener(this);
        line_intro.setOnClickListener(this);
        //signature_textview.setOnClickListener(this);
       // intro_textview.setOnClickListener(this);
        //select_pic.setOnClickListener(this);
        profile_back.setOnClickListener(this);
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWidth = outMetrics.widthPixels;
        int  mScreenHeight = outMetrics.heightPixels;
//       System.out.println("mScreenWidth==="+mScreenWidth);
//        System.out.println("mScreenHeight==="+mScreenHeight);


    }
    private  LWNModel_lawyerInfo lawyerInfo = null;
    private void setData(){
        BitmapUtils bitmapUtils = new BitmapUtils(activity);
        bitmapUtils.configDefaultLoadingImage(R.drawable.qd_youtouxiang);//默认背景图片
        bitmapUtils.configDefaultLoadFailedImage(R.drawable.qd_youtouxiang);//加载失败图片
        bitmapUtils.display(select_picView, lawyerInfo.getHead_src());
//        if(photo!=null){
//            select_picView.setImageBitmap(photo);
//        }
        intro_textview.setText(lawyerInfo.getIntro());
        signature_textview.setText(lawyerInfo.getSignatu());
        real_name.setText(lawyerInfo.getRealname());

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.line_signature:
                Intent signatureintent=new Intent();
                signatureintent.setClass(this,LWNSignatureActivity.class);
                Bundle signaturebundle=new Bundle();
                signaturebundle.putInt("index",1);
                if(lawyerInfo!=null){
                    signaturebundle.putString("content",lawyerInfo.getSignatu());
                }else{
                    signaturebundle.putString("content","");
            }
                //signaturebundle.putString("content",lawyerInfo.getSignatu());
                signatureintent.putExtras(signaturebundle);
                startActivity(signatureintent);
            break;
            case R.id.line_intro:
                Intent introintent=new Intent();
                introintent.setClass(this,LWNSignatureActivity.class);
                Bundle introbundle=new Bundle();
                introbundle.putInt("index",2);
                if(lawyerInfo!=null){
                    introbundle.putString("content",lawyerInfo.getIntro());
                }else{
                    introbundle.putString("content","");
                }
               // introbundle.putString("content",lawyerInfo.getIntro());
                introintent.putExtras(introbundle);
                startActivity(introintent);
                break;
            case R.id.line_pic:{
                KFWActivityCenter.getInstance().setTakephoto_state(0);
                Intent intent = new Intent();
                intent.setClass(this, PhotoSelectorActivity.class);
                startActivityForResult(intent, 210);
                //inItData();
            }break;
            case R.id.profile_back:
                finish();
                break;
        }

    }

   private void inItData(){
       new AlertDialog.Builder(this).setTitle("请选择").setItems(items,new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
               switch (which){
                   case 0:
                       Intent intent = new Intent();
                       intent.setData(Uri.parse("content://media/internal/images/media"));
                       intent.setAction(Intent.ACTION_PICK);
                       startActivityForResult(Intent.createChooser(intent, "Select Picture"), 001);
                       break;
                   case 1:
                       String SDState = Environment.getExternalStorageState();
                       if(SDState.equals(Environment.MEDIA_MOUNTED)){
                           Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
                           startActivityForResult(i, 002);
                       }else{
                           Toast.makeText(activity, "请检查SD卡是否正确", Toast.LENGTH_LONG)
                                   .show();
                       }
                   break;
               }
           }
       }).create().show();
   }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 210: {
                if (resultCode != 50) {
//                    ToastView_custom toast = new ToastView_custom(activity);
//                    toast.showCustom(activity, getResources().getDrawable(R.drawable.error), "保存失败，请重新拍照更换");
                    return;
                }
                try {
                    final ArrayList<PhotoModel> array_path = (ArrayList<PhotoModel>) data.getSerializableExtra("photos");
                    String path = "file://" + array_path.get(0).getOriginalPath();
                    if (array_path != null) {
                        ImageLoader.getInstance().loadImage(path, new SimpleImageLoadingListener() {
                            @Override
                            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                //iv_edit_header.setImageBitmap(loadedImage);
                                photo = loadedImage;
                                updePhoto(array_path.get(0).getOriginalPath());
                            }

                            @Override
                            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//                                ToastView_custom toast = new ToastView_custom(activity);
//                                toast.showCustom(activity, getResources().getDrawable(R.drawable.error), "保存失败，请重新拍照更换");

                                ToastView_custom toast = new ToastView_custom(activity);
                                toast.showCustom(activity, "保存失败，请重新拍照更换");
                            }
                        });
                        //changeInfo();
                        //upLoadPic();
                    }
                } catch (Exception e) {
//                    ToastView_custom toast = new ToastView_custom(activity);
//                    toast.showCustom(activity, getResources().getDrawable(R.drawable.error), "保存失败，请重新拍照更换");

                    ToastView_custom toast = new ToastView_custom(activity);
                    toast.showCustom(activity, "保存失败，请重新拍照更换");
                }
            }
            break;
        }
    }

    private void updePhoto(String imagedir){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(activity, "", getResources().getString(R.string.toast_send));
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        RequestParams params = center.updePhoto(activity,imagedir);
        String url=center.LWNBaseUrl_POST+"/updatelawyphoto";
        HttpUtils http=center.getUtils();
        http.send(HttpRequest.HttpMethod.POST,url,params,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                proDialog.dismiss();
                try{
                    JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                    String string_code = jsonObject.getString("code");
                    String string_msg = jsonObject.getString("msg");

                    ToastView_custom toast = new ToastView_custom(activity);

                    switch (Integer.parseInt(string_code)) {
                        case 10000:{
                            toast.showCustom(activity,  string_msg);
                            BitmapUtils bitmapUtils = new BitmapUtils(activity);
                            bitmapUtils.configDefaultLoadingImage(R.drawable.qd_youtouxiang);//默认背景图片
                            bitmapUtils.configDefaultLoadFailedImage(R.drawable.qd_youtouxiang);//加载失败图片
                            bitmapUtils.display(select_picView, lawyerInfo.getHead_src());
                            if(photo!=null){
                                select_picView.setImageBitmap(photo);
                            }
                        }break;
                        default:{
                            toast.showCustom(activity,  string_msg);
                        }break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                proDialog.dismiss();

                ToastView_custom toast = new ToastView_custom(activity);
                toast.showCustom(activity, "保存失败，请重新拍照更换");
            }
        });


    }

    private void SavePicInLocal(Bitmap bitmap){
        FileOutputStream fos=null;
        BufferedOutputStream bos = null;
        ByteArrayOutputStream baos = null;
        try{
            // 获取 SD 卡根目录
            String saveDir = Environment.getExternalStorageDirectory() + "/meitian_photos";
            // 新建目录
            File dir = new File(saveDir);
            if (! dir.exists()) dir.mkdir();
            // 生成文件名
            SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS");
            String filename = "MT" + (t.format(new Date())) + ".jpg";
            // 新建文件
            File file = new File(saveDir, filename);
            // 打开文件输出流
            fos = new FileOutputStream(file);
            // 生成图片文件
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            // 相片的完整路径
            this.picPath = file.getPath();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (baos != null) {
                   try {
                       baos.close();
                          } catch (Exception e) {
                                e.printStackTrace();
                               }
                      }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }


    }

    /**
     * 刷新数据
     */
    private void refreshData(){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(this, "", getResources().getString(R.string.toast_wait));
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(this)){
            ToastView_custom toast = new ToastView_custom(this);
            toast.showCustom(this, "请检查网络，稍后重试");
//            home_gooddata_refresh.setRefreshing(false);
//            home_gooddata_refresh.setLoading(false);
            proDialog.dismiss();
            return;
        }
        String string_url = center.getInstance().getLawyerInfo(this);
        HttpUtils http = center.getUtils();
        http.configCurrentHttpCacheExpiry(0*0);
        http.send(HttpRequest.HttpMethod.GET,string_url,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                proDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                    String string_code = jsonObject.getString("code");
                    String string_msg = jsonObject.getString("msg");
                    switch (Integer.parseInt(string_code)) {
                        case 10000: {
                            JSONObject json_object = jsonObject.getJSONObject("data");
                            lawyerInfo=LWNJsonToData.saveLawyerInfoWithJsonString(json_object);
                            setData();
                        }
                        break;
                        case 10001: {
//                            Toast toast = Toast.makeText(activity.getApplicationContext(),
//                                    string_msg, Toast.LENGTH_SHORT);
//                            toast.setGravity(Gravity.CENTER, 0, 0);
//                            LinearLayout toastView = (LinearLayout) toast.getView();
//                            ImageView imageCodeProject = new ImageView(activity.getApplicationContext());
//                            imageCodeProject.setImageResource(R.drawable.error);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();
                            ToastView_custom toast = new ToastView_custom(LWNEditProfileActivity.this);
                            toast.showCustom(LWNEditProfileActivity.this, string_msg);
                        }
                        break;
                        case 10003: {
                            String token = LWNModel_user.getInstance().getString_token(activity);
                            if (token != null) {
//                                Toast toast = Toast.makeText(activity.getApplicationContext(),
//                                        string_msg, Toast.LENGTH_SHORT);
//                                toast.setGravity(Gravity.CENTER, 0, 0);
//                                LinearLayout toastView = (LinearLayout) toast.getView();
//                                ImageView imageCodeProject = new ImageView(activity.getApplicationContext());
//                                imageCodeProject.setImageResource(R.drawable.error);
//                                toastView.addView(imageCodeProject, 0);
//                                toast.show();
                                ToastView_custom toast = new ToastView_custom(LWNEditProfileActivity.this);
                                toast.showCustom(LWNEditProfileActivity.this, string_msg);
//                                Intent intent = new Intent();
//                                intent.setClass(activity, LWNLoginActivity.class);
//                                startActivity(intent);
                                setResult(300);
                                finish();
                            }
                        }
                        break;
                        default: {
//                            Toast toast = Toast.makeText(activity.getApplicationContext(),
//                                    string_msg, Toast.LENGTH_SHORT);
//                            toast.setGravity(Gravity.CENTER, 0, 0);
//                            LinearLayout toastView = (LinearLayout) toast.getView();
//                            ImageView imageCodeProject = new ImageView(activity.getApplicationContext());
//                            imageCodeProject.setImageResource(R.drawable.error);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();
                            ToastView_custom toast = new ToastView_custom(LWNEditProfileActivity.this);
                            toast.showCustom(LWNEditProfileActivity.this, string_msg);
                        }
                        break;
                    }

                } catch (Exception e) {
                    proDialog.dismiss();
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                proDialog.dismiss();
            }
        });


    }



    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}
